import store from "../store/index";

let audio = new Audio();

// 播放歌曲
audio.playSong = async function(id) {
  store.dispatch("get_song_detail", id);
  store.dispatch("get_song_lyric", id);
  audio.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`;
  audio.oncanplay = function() {
    audio.play();
  };
};

// 暂停或播放
audio.playStatus = function() {
  if (this.paused) {
    this.play();
  } else {
    this.pause();
  }
};

// 将音频播放状态 和 相关信息存至 vuex 中，方便多页面使用
audio.addEventListener("playing", () => {
  // console.log("播放中");
  store.commit("change_playing", true);
});
audio.addEventListener("pause", () => {
  // console.log("暂停");
  store.commit("change_playing", false);
});

// 监听音频的改变
audio.addEventListener("timeupdate", () => {
  // 音频改变滚动条
  // console.log(Math.round(audio.currentTime));

  if (!store.state.drag_status) {
    store.commit("change_progress", audio.currentTime);
  }
  if (store.state.scroll_lyric) {
    let idx = store.state.medisArray.findIndex((el) => {
      return el.t == Math.round(audio.currentTime);
    });
    if (idx !== -1) {
      store.commit("change_offset", idx);
    }
  }
});
// 歌曲播放结束
audio.addEventListener("ended", () => {
  let new_idx;
  if (store.state.song_idx === store.state.play_list.length - 1) {
    new_idx = 0;
  } else {
    new_idx = store.state.song_idx + 1;
  }
  let next_id = store.state.play_list[new_idx];
  // 改变当前歌曲下标
  store.commit("change_idx", new_idx);
  // 拿到id后进行歌曲播放，并且更新歌曲详情
  audio.playSong(next_id);
});

export default audio;
